import { Component, Vue, Watch } from 'vue-property-decorator'
import { State, Action, Mutation } from 'vuex-class'
import styles from './styles.less'
import Timeline from '@/components/timeline/index'
import TimelineItem from '@/components/timeline/TimelineItem'
import ApplyInvoiceDialog from '@/components/applyInvoiceDialog/ApplyInvoiceDialog'
import {
  formatStatus,
  userLicenseTypes,
  adminTypes,
  orgLicenseTypes,
  sealTypes,
  useTypes,
  orgTypes,
  // opts,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import ApplyDetail from './../NewApply/ApplyDetail'
import { RootState } from '@/store'
import RefundDialog from '@/views/NewApply/refundDialog'

const moduleTipsList: any = {
  tips21:
    '温馨提示：统付方审核时间在1个工作日内，如需加急或者超期未处理，请联系统付方审核。', // 待统付方审核时提示
}

@Component({})
export default class ApplyFlow extends Vue {
  private orderNo: any = null
  private sealApplyId: any = null
  operations: any[] = []
  private activeOperation: number = -1 // 当前步骤进度
  private sealApplyStatus: number = -1 // 工单状态
  private disabledRefundBtn: boolean = false
  applyInvoiceDialogVisible: boolean = false
  private payOrderId: number = 0
  private applyInvoiceDisable: boolean = false
  private payType: number = -1
  private invoiceStatus: number = -1
  private showInfoVisible: boolean = false // 查看统付方信息弹窗
  private payOrgName: string = ''
  private payOrgManager: string = ''
  private payOrgPhone: string = ''
  private payerOrganizeUUID: string = ''

  @State((state: RootState) => state.newApply.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.newApply.applyData) private applyData!: any
  @Mutation('newApply/setStateData') private setStateData!: (data: any) => {}
  @Action('newApply/sealDetail') private sealDetail!: any
  @Action('newApply/querySealApplyOps') private querySealApplyOps!: any

  @State((state: RootState) => state.newApply.refundDialogVisible)
  private refundDialogVisible!: boolean
  @State((state: RootState) => state.newApply.refundData)
  private refundData!: any
  @Action('newApply/sealRefund') private sealRefund!: any
  @Action('newApply/receiptConfirm') private receiptConfirm!: any
  @Action('paymentOrder/invoiceDirect') private invoiceDirect!: any
  @Action('user/payOrganizeDataMasking') private payOrganizeDataMasking!: any

  get showApplyInvoiceButton() {
    // 是否显示开票按钮-自付费且未开票
    return this.payType !== 2 && this.invoiceStatus !== 2
  }

  get showDownloadInvoiceButton() {
    // 是否显示下载发票按钮-自付费且已开票
    return this.payType !== 2 && this.invoiceStatus === 2
  }

  @Watch('applyInvoiceDialogVisible')
  onApplyInvoiceDialogVisibleChange(v: boolean) {
    if (!v) {
      this.getOptions()
    }
  }

  protected render() {
    return (
      <div class={styles.container}>
        <h4 class={styles.head}>
          印章申请信息
          <el-button
            type="text"
            class={{ [styles.btn]: true, [styles.btnText]: true }}
            onClick={this.detail}
          >
            <span class={styles.detailImg} />
            详情
          </el-button>
          <router-link
            to="/home/newApply"
            class={{ [styles.link]: true, [styles.btn]: true }}
          >
            <span class={styles.backImg} />
            印章申请列表
          </router-link>
        </h4>
        <div class={styles.timeline}>
          <Timeline style="width: 880px;">
            {this.operations &&
              this.operations.map((item: any, index: number) => (
                <TimelineItem
                  pointColor={
                    item.active || item.finished ? '#0975E1' : '#E4E4E4'
                  }
                  bgColor={
                    item.active || item.finished
                      ? '#ffffff'
                      : 'rgb(245, 247, 249)'
                  }
                  shadow={item.active ? 'rgba(0,0,0,0.1)' : undefined}
                  id={item.active ? 'activeStep' : ''}
                  class={{
                    finish: item.finished && !item.active,
                    active: item.active,
                  }}
                  lineColor={item.active ? '#D8E9FA' : undefined}
                  borderColor={
                    item.active ? '#0975E1' : item.finished ? '#ECEEF6' : ''
                  }
                >
                  <p>
                    <span class={styles.title}>
                      {/* {formatStatus(opts, item.operatorModule)} */}
                      {item.operatorModuleName}
                    </span>
                    <span class={styles.time}>{this.getTimes(item)}</span>
                  </p>
                  {this.showLine(item) &&
                    item.ops.map((op: any, i: number) => (
                      <div>
                        <p class={styles.opt}>
                          <span
                            class={[
                              { red: this.isRejectStatus(op.operatorType) },
                            ]}
                          >
                            {op.operatorTypeName}
                          </span>
                          <span class={styles.time}>{op.time}</span>
                        </p>
                        {/* 当前步骤为待统付方审核 */}
                        {this.getTips(op.operatorType) &&
                          item.active &&
                          i === item.ops.length - 1 && (
                            <p class={styles.tips}>
                              {this.getTips(op.operatorType)}
                              <el-button
                                type="text"
                                class="ml10 pd0"
                                onClick={this.showInfo}
                              >
                                查看统付方联系方式
                              </el-button>
                            </p>
                          )}
                        {this.isRejectStatus(op.operatorType) && (
                          <p class={[styles.opt, { [styles.act]: true }]}>
                            <p
                              class={[
                                styles.reason,
                                { [styles.more]: !op.more },
                              ]}
                            >
                              <span>退回原因：</span>
                              <span>{op.content}</span>
                              <i
                                class={
                                  op.more
                                    ? 'el-icon-arrow-up'
                                    : 'el-icon-arrow-down'
                                }
                                title={op.more ? '收起' : '展开'}
                                onClick={() => {
                                  this.more(index, i, !op.more)
                                }}
                              />
                            </p>
                          </p>
                        )}
                      </div>
                    ))}
                  <p class={styles.operation}>
                    {/* 当且仅当工单状态不为撤回状态,显示查看关联订单 */}
                    {this.showOrderInfo(item) && (
                      <div>
                        <el-tooltip placement="bottom-start">
                          <p slot="content" class="w216">
                            前往“我的订单”查看物流与下载发票
                          </p>
                          <el-button
                            type="text"
                            onClick={this.toOrderPage}
                            class={
                              this.showApplyInvoiceButton ||
                              this.showDownloadInvoiceButton
                                ? 'block-button'
                                : ''
                            }
                          >
                            查看关联订单
                          </el-button>
                        </el-tooltip>
                        {this.showApplyInvoiceButton && (
                          <el-button
                            type="text"
                            onClick={this.applyInvoice}
                            disabled={this.applyInvoiceDisable}
                            class="block-button"
                          >
                            申请开票
                          </el-button>
                        )}
                        {this.showDownloadInvoiceButton && (
                          <el-button
                            type="text"
                            onClick={this.downloadInvoice}
                            class="block-button"
                          >
                            下载发票
                          </el-button>
                        )}
                      </div>
                    )}
                    {/* 修改 */}
                    {((item.operatorModule === 3 && !this.getTimes(item)) ||
                      (item.operatorModule === 1 &&
                        this.sealApplyStatus === 93)) &&
                      item.active && (
                        <el-button type="text" onClick={this.toEdit}>
                          修改
                        </el-button>
                      )}
                    {item.operatorModule === 3 && item.active && (
                      <el-button type="text" onClick={this.revoke}>
                        撤回
                      </el-button>
                    )}
                    {item.operatorModule === 0 &&
                      this.activeOperation === 0 &&
                      !!this.payOrderId && (
                        <el-button type="text" onClick={this.toOrderPage}>
                          查看退款情况
                        </el-button>
                      )}
                    {/* 待收货状态 */}
                    {item.operatorModule === 5 &&
                      this.activeOperation === 5 &&
                      this.sealApplyStatus === 28 && (
                        <p class={styles.operation}>
                          <el-button
                            type="text"
                            onClick={this.toOrderPage}
                            class="block-button"
                          >
                            查看物流
                          </el-button>
                          <el-button
                            type="text"
                            onclick={this.takeOver}
                            class="block-button"
                          >
                            确认收货
                          </el-button>
                        </p>
                      )}
                  </p>
                </TimelineItem>
              ))}
          </Timeline>
        </div>
        <ApplyDetail
          onVisibleChange={(val: boolean) => {
            this.setStateData({ detailVisible: val })
          }}
          visible={this.detailVisible}
          defaultData={this.applyData}
        />
        <RefundDialog
          visible={this.refundDialogVisible}
          defaultData={this.refundData}
          type="newApply"
          disabled={this.disabledRefundBtn}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ refundDialogVisible: val })
          }}
          onSubmit={this.confirmRefund}
        />
        <ApplyInvoiceDialog
          dialogVisible={this.applyInvoiceDialogVisible}
          payOrderId={this.payOrderId}
          {...{
            on: {
              'update:dialogVisible': this.setDialogVisible,
              success: this.getOptions,
            },
          }}
        />
        <el-dialog
          title="统付方联系方式"
          width="420px"
          visible={this.showInfoVisible}
          custom-class={styles.infoDialog}
          close-on-click-modal={false}
          close-on-press-escape={false}
          {...{
            on: {
              'update:visible': (val: boolean) => {
                this.showInfoVisible = val
              },
            },
          }}
        >
          <p>统一付费方：{this.payOrgName}</p>
          <p>付费方管理员：{this.payOrgManager}</p>
          <p>联系方式：{this.payOrgPhone}</p>
          <p slot="footer">
            <el-button
              onClick={() => {
                this.showInfoVisible = false
              }}
            >
              关闭
            </el-button>
          </p>
        </el-dialog>
      </div>
    )
  }
  setDialogVisible(val: boolean) {
    this.applyInvoiceDialogVisible = val
  }

  detail() {
    this.sealDetail(this.sealApplyId).then((data: any) => {
      this.setStateData({
        detailVisible: true,
        applyData: Object.assign({}, data, {
          agentLicenseType: formatStatus(
            userLicenseTypes,
            data.agentLicenseType
          ),
          applyOrganizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
          applyOrganizeLicenseType: formatStatus(
            orgLicenseTypes,
            data.applyOrganizeLicenseType
          ),
          applyOrganizeType: formatStatus(orgTypes, data.applyOrganizeType),
          confirmOrganizeLicenseType: formatStatus(
            orgLicenseTypes,
            data.confirmOrganizeLicenseType
          ),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
          agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
          agentMobileDes: desensitization(data.agentMobile || ''),
          orderNo: data.orderNo,
        }),
      })
      //   this.sealOption = getTimeline(data.sealApplyStatus, this.applyData);
    })
  }

  private mounted() {
    this.sealApplyId = this.$route.query.id || ''
    if (this.$route.query.payType) {
      this.payType = parseInt(this.$route.query.payType.toString())
    }
    this.getOptions()
  }

  isRejectStatus(status: number) {
    return [90, 91, 92, 97].indexOf(status) !== -1
  }

  more(index: number, i: number, isMore: boolean) {
    // 展开or收起
    this.$set(this.operations[index].ops[i], 'more', isMore)
  }

  showOrderInfo(item: any) {
    return (
      item.operatorModule === 1 && this.activeOperation !== 0 && !item.active
    )
  }

  getOptions() {
    this.querySealApplyOps(this.sealApplyId).then((res: any) => {
      // res = {"errCode":0,"errorCode":"","msg":"SUCCESS","data":{"modules":[{"ops":[{"operatorType":20,"content":"","time":"2020-05-27 18:16:05","operatorTypeName":"支付完成"}],"operatorModule":1,"operatorModuleName":"支付完成","operatorTime":"2020-05-27 18:16:05","finish":2},{"ops":[{"operatorType":2,"content":"","time":"2020-05-27 18:16:05","operatorTypeName":"发起申请"}],"operatorModule":2,"operatorModuleName":"发起申请","operatorTime":"2020-05-27 18:16:05","finish":1},{"ops":[],"operatorModule":3,"operatorModuleName":"材料审核","operatorTime":null,"finish":1},{"ops":[],"operatorModule":4,"operatorModuleName":"印章制证与备案","operatorTime":null,"finish":1},{"ops":[],"operatorModule":5,"operatorModuleName":"发货与收货","operatorTime":null,"finish":1},{"ops":[],"operatorModule":6,"operatorModuleName":"完成","operatorTime":null,"finish":1}],"payOrderId":950546,"sealApplyId":41806,"sealApplyStatus":2,"orderNo":"T2020052751336","logisticsNumber":"","invoiceStatus":1},"errShow":true}
      this.invoiceStatus = res.data.invoiceStatus
      this.payOrderId = res.data.payOrderId
      this.orderNo = res.data.orderNo
      this.payerOrganizeUUID = res.data.unifiedOrganizeUuid
      this.sealApplyStatus = res.data.sealApplyStatus
      this.operations = res.data.modules.map((modules: any, index: number) => {
        const active = modules.finish === 2 // 1未处理、2处理中、3已处理
        const breakon =
          res.data.modules[index + 1] &&
          res.data.modules[index + 1].finish === 1 &&
          modules.finish === 3
        const lastFinish =
          index === res.data.modules.length - 1 && modules.finish === 3 // 最后一个true为active
        const finished = modules.finish === 3
        this.activeOperation =
          active || lastFinish || breakon
            ? modules.operatorModule
            : this.activeOperation

        return {
          ...modules,
          active: active || lastFinish || breakon || false,
          finished,
        }
      })

      this.$nextTick(() => {
        const el = this.$el.querySelector('#activeStep') as Element
        if (!!el) {
          // 定位页面中间
          el.scrollIntoView({ block: 'center', behavior: 'smooth' })
        }
      })
    })
  }

  getTimes(item: any) {
    if (this.showLine(item)) {
      if (
        item.ops.findIndex(
          (op: any) =>
            op.operatorType === 90 ||
            op.operatorType === 91 ||
            op.operatorType === 92 ||
            op.operatorType === 97
        ) !== -1
      ) {
        return ''
      }

      return item.operatorModule === 3
        ? '（1个工作日以内）'
        : item.operatorModule === 4
        ? '（2个工作日以内）'
        : item.operatorModule === 5
        ? '（以实际物流时间为准）'
        : ''
    }

    return item.operatorTime || ''
  }

  private showLine(item: any) {
    // 哪些模块展示子模块
    return (
      [1, 3, 4, 5].indexOf(item.operatorModule) !== -1 &&
      (item.finish || item.active)
    )
  }

  getTips(module: any) {
    return moduleTipsList[`tips${module}`] || ''
  }

  takeOver() {
    this.receiptConfirm(this.sealApplyId).then(async () => {
      this.$message.success('已确认收货')
      this.getOptions()
    })
  }

  applyInvoice() {
    this.applyInvoiceDisable = true
    this.invoiceDirect(this.payOrderId)
      .then(() => {
        this.applyInvoiceDialogVisible = true
      })
      .finally(() => {
        this.applyInvoiceDisable = false
      })
  }

  showInfo() {
    this.payOrganizeDataMasking({
      uuid: this.payerOrganizeUUID,
    }).then((res: any) => {
      this.showInfoVisible = true
      this.payOrgPhone = res.data.contactPhone || ''
      this.payOrgManager = res.data.contactName || ''
      this.payOrgName = res.data.payOrganizeName || ''
    })
  }

  downloadInvoice() {
    this.applyInvoiceDialogVisible = true
  }

  toOrderPage() {
    this.$router.push({
      name: 'myOrderList',
      params: { type: 'all' },
      query: { orderNo: !!this.orderNo ? this.orderNo : undefined },
    })
  }

  toEdit() {
    this.$router.push({
      name: 'applyPage',
      params: { type: 'newApply' },
      query: { id: this.sealApplyId },
    })
  }

  revoke() {
    this.sealDetail(this.sealApplyId).then((data: any) => {
      this.setStateData({
        refundDialogVisible: true,
        refundData: data,
      })
    })
  }

  confirmRefund(data: any) {
    console.log({ ...data })
    this.disabledRefundBtn = true
    this.sealRefund({ ...data })
      .then((res: any) => {
        this.disabledRefundBtn = false
        this.$message.success('申请撤回成功')
        this.setStateData({
          refundDialogVisible: false,
        })
        this.getOptions()
        //   this.query();
      })
      .catch((err: any) => {
        this.disabledRefundBtn = false
      })
  }
}
